<script setup>
import { onMounted, reactive, ref, toRaw, watch } from 'vue'
import { queryCompleteCategoryList } from '@/service/category.js'
import { ElTreeSelect } from 'element-plus'
import { queryCouponProductInfo, searchProduct } from '@/service/product.js'
import { ElMessage } from 'element-plus'
import { addNewCoupon, updateCoupon } from '@/service/coupon.js'
import dayjs from 'dayjs'
const props = defineProps({
  type: {
    type: String,
    required: true,
    default: 'add',
  },
  data: {
    type: Object,
    required: false,
  },
})
// 控制是否展示对话框
const showCouponModal = ref(false)

let couponForm = reactive({
  id: null, // 优惠券ID
  name: null, // 优惠券名字
  distributionTime: null, // 优惠券发放时间
  couponType: 0, // 优惠类型0 - 通用券，1 - 品类券，2 商品券
  categoryIds: null, // 优惠券关联分离ID
  productIds: null, // 优惠券关联商品ID
  denomination: 5, //优惠券面额,
  hasThreshold: 0, // 是否有使用门槛
  threshold: 5, //使用门槛
  expiryType: 0, //有效期类型
  validDays: 7, // 有效天数
  availableTime: null, // 有效时间
  hasQuantityLimit: 0, // 是否有数量限制
  quantityLimit: 100, // 数量限制(如果有)
  userMaxCollectionLimit: 1, //用户最大领取限制
  couponStatus: 0, //优惠券状态 0 - 正常，1 - 关闭，2 - 过期，3 - 删除
  productList: null, // 商品列表
})
watch(showCouponModal, async (newVal) => {
  if (!newVal) {
    Object.assign(couponForm, {
      id: null, // 优惠券ID
      name: null, // 优惠券名字
      distributionTime: null, // 优惠券发放时间
      couponType: 0, // 优惠类型0 - 通用券，1 - 品类券，2 商品券
      categoryIds: null, // 优惠券关联分离ID
      productIds: null, // 优惠券关联商品ID
      denomination: 5, //优惠券面额,
      hasThreshold: 0, // 是否有使用门槛
      threshold: 5, //使用门槛
      expiryType: 0, //有效期类型
      validDays: 7, // 有效天数
      availableTime: null, // 有效时间
      hasQuantityLimit: 0, // 是否有数量限制
      quantityLimit: 100, // 数量限制(如果有)
      userMaxCollectionLimit: 1, //用户最大领取限制
      couponStatus: 0, //优惠券状态 0 - 正常，1 - 关闭，2 - 过期，3 - 删除
      productList: null, // 商品列表
    })
  } else if (newVal && props.type === 'edit') {
    const couponInfo = toRaw(props.data)
    Object.assign(couponForm, couponInfo)
    couponForm.distributionTime = [new Date(couponInfo.distributionStartTime), new Date(couponInfo.distributionEndTime)]
    // 如果是商品券，修改商品信息
    if (couponForm.couponType === 2) {
      const res = await queryCouponProductInfo(couponInfo.productIds)
      couponForm.productList = res.data
    }
    if (couponForm.expiryType === 1) {
      couponForm.availableTime = [new Date(couponInfo.availableStartTime), new Date(couponInfo.availableEndTime)]
    }
  }
})
// 分类列表
const categoryList = ref([])
const productCurrentPage = ref(1)
const productPageSize = ref(10)
const productTotal = ref(0)
onMounted(async () => {
  let res = await queryCompleteCategoryList()
  categoryList.value = res.data
  res = await searchProduct(
    productSearchForm.productName,
    'all',
    null,
    null,
    0,
    productCurrentPage.value,
    productPageSize.value
  )
  productList.value = res.data.records
  productTotal.value = res.data.total
})
// 暴露给父组件的属性
defineExpose({
  couponForm,
  showCouponModal,
})
const showProductSelectDialog = ref(false)
const cascaderProps = {
  value: 'id',
  label: 'name',
  children: 'children',
}

const productSearchForm = reactive({
  productName: '',
})
const productList = ref([])
async function onTapSelectProduct() {
  showProductSelectDialog.value = true
}

watch([productCurrentPage, productPageSize], async () => {
  const res = await searchProduct(
    productSearchForm.productName,
    'all',
    null,
    null,
    0,
    productCurrentPage.value,
    productPageSize.value
  )
  productList.value = res.data.records
  productTotal.value = res.data.total
})

async function onTapSearchProductButton() {
  const res = await searchProduct(
    productSearchForm.productName,
    'all',
    null,
    null,
    0,
    productCurrentPage.value,
    productPageSize.value
  )
  productList.value = res.data.records
  productTotal.value = res.data.total
}
const productTableRef = ref()
async function onTapConfirmProduct() {
  couponForm.productList = productTableRef.value.getSelectionRows()
  showProductSelectDialog.value = false
}
function onTapDeleteProductButton(row) {
  const index = couponForm.productList.findIndex((item) => item.id === row.id)
  if (index !== -1) {
    couponForm.productList.splice(index, 1)
  }
}

watch(
  () => couponForm.productList,
  () => {
    if (couponForm.productList && couponForm.productList.length > 0) {
      couponForm.productIds = couponForm.productList.map((item) => item.id)
    }
  }
)

function validCouponForm() {
  // 校验优惠券名字
  if (!couponForm.name) {
    ElMessage.error('请输入优惠券名字！')
    return false
  }
  // 校验发放时间
  if (!couponForm.distributionTime) {
    ElMessage.error('请填写优惠券发放时间！')
    return false
  }
  const distributionEndTime = couponForm.distributionTime[1]
  if (distributionEndTime.getTime() < new Date().getTime()) {
    ElMessage.error('请确认优惠券发放时间是否合理！')
    return false
  }
  // 如果是品类券，必须要关联品类
  if (couponForm.couponType === 1 && (!couponForm.categoryIds || couponForm.categoryIds.length <= 0)) {
    ElMessage.error('请确认是否已经关联品类！')
    return false
  }
  // 如果是商品券，必须关联商品
  if (couponForm.couponType === 2 && (!couponForm.productIds || couponForm.productIds.length <= 0)) {
    ElMessage.error('请确认是否已经关联商品！')
    return false
  }
  // 如果订单有使用门槛，判断使用门槛是否合理
  if (couponForm.hasThreshold === 1 && couponForm.denomination > couponForm.threshold) {
    if (!couponForm.threshold) {
      ElMessage.error('请添加使用门槛！')
      return false
    }
    if (couponForm.denomination > couponForm.threshold) {
      ElMessage.error('请确认优惠券面额是否合理！')
      return false
    }
  }
  // 如果订单的使用时间类型为时间段，判断时间段是否合理
  if (couponForm.expiryType === 1 && !couponForm.availableTime) {
    ElMessage.error('请填写优惠券可用的时间范围！')
    return false
  }
  if (couponForm.expiryType === 1 && couponForm.availableTime) {
    const availableEndTime = couponForm.availableTime[1]
    if (availableEndTime.getTime() < new Date().getTime()) {
      ElMessage.error('请确认优惠券的有效时间是否合理！')
      return false
    }
  }
  // 如果是限量优惠券，用户最大可领取数量不可以多于优惠券总数量
  if (couponForm.hasQuantityLimit === 0 && couponForm.quantityLimit < couponForm.userMaxCollectionLimit) {
    ElMessage.error('请确认用户可领取数量是否合理！')
    return false
  }

  return true
}
const emits = defineEmits(['update'])
async function onTapSaveButton() {
  if (!validCouponForm()) {
    return
  }
  const form = toRaw(couponForm)
  const params = {}
  params.id = form.id
  params.name = form.name
  params.distributionStartTime = dayjs(form.distributionTime[0]).format('YYYY-MM-DD HH:mm:ss')
  params.distributionEndTime = dayjs(form.distributionTime[1]).format('YYYY-MM-DD HH:mm:ss')
  params.couponType = form.couponType
  params.categoryIds = form.categoryIds
  params.productIds = form.productIds
  params.denomination = form.denomination
  params.hasThreshold = form.hasThreshold
  params.threshold = form.threshold
  params.expiryType = form.expiryType
  if (params.expiryType === 1) {
    params.availableStartTime = dayjs(form.availableTime[0]).format('YYYY-MM-DD HH:mm:ss')
    params.availableEndTime = dayjs(form.availableTime[1]).format('YYYY-MM-DD HH:mm:ss')
  }
  params.validDays = form.validDays
  params.hasQuantityLimit = form.hasQuantityLimit
  params.quantityLimit = form.quantityLimit
  params.userMaxCollectionLimit = form.userMaxCollectionLimit
  params.couponStatus = form.couponStatus
  await addNewCoupon(params)
  emits('update')
  showCouponModal.value = false
  ElMessage.success('成功添加优惠券！')
}
async function onTapUpdateButton() {
  if (!validCouponForm()) {
    return
  }
  const form = toRaw(couponForm)
  const params = {}
  params.id = form.id
  params.name = form.name
  params.distributionStartTime = dayjs(form.distributionTime[0]).format('YYYY-MM-DD HH:mm:ss')
  params.distributionEndTime = dayjs(form.distributionTime[1]).format('YYYY-MM-DD HH:mm:ss')
  params.couponType = form.couponType
  params.categoryIds = form.categoryIds
  params.productIds = form.productIds
  params.denomination = form.denomination
  params.hasThreshold = form.hasThreshold
  params.threshold = form.threshold
  params.expiryType = form.expiryType
  if (params.expiryType === 1) {
    params.availableStartTime = dayjs(form.availableTime[0]).format('YYYY-MM-DD HH:mm:ss')
    params.availableEndTime = dayjs(form.availableTime[1]).format('YYYY-MM-DD HH:mm:ss')
  }
  params.validDays = form.validDays
  params.hasQuantityLimit = form.hasQuantityLimit
  params.quantityLimit = form.quantityLimit
  params.userMaxCollectionLimit = form.userMaxCollectionLimit
  params.couponStatus = form.couponStatus
  await updateCoupon(params)
  emits('update')
  showCouponModal.value = false
  ElMessage.success('成功更新优惠券！')
}
</script>

<template>
  <el-dialog
    v-model="showCouponModal"
    :close-on-click-modal="false"
    :title="type === 'add' ? '新增优惠券' : '编辑优惠券'"
    draggable
    style="width: 800px"
  >
    <el-scrollbar height="500px">
      <el-form :model="couponForm" label-position="right" label-width="100px">
        <!-- 优惠券名称 -->
        <el-form-item label="优惠券名称:">
          <el-input v-model="couponForm.name" placeholder="请输入优惠券名称" style="width: 500px"></el-input>
        </el-form-item>

        <el-form-item label="发放时间:">
          <div style="display: flex; flex-direction: column">
            <el-date-picker
              v-model="couponForm.distributionTime"
              class="publish-time-picker"
              end-placeholder="结束时间"
              range-separator="至"
              start-placeholder="开始时间"
              style="width: 450px"
              type="datetimerange"
              unlink-panels
            />
            <div style="font-size: 12px; color: #999">优惠券开始发放和结束发放时间</div>
          </div>
        </el-form-item>

        <!-- 优惠券类型 -->
        <el-form-item label="优惠券类型:" style="margin-top: -20px">
          <el-radio-group v-model="couponForm.couponType">
            <el-radio :value="0">通用券</el-radio>
            <el-radio :value="1">品类券</el-radio>
            <el-radio :value="2">商品券</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 不同类型优惠券的配置项（占位） -->
        <template v-if="couponForm.couponStatus === 0"> </template>
        <template v-if="couponForm.couponType === 1">
          <el-form-item>
            <div style="display: flex; flex-direction: column">
              <el-tree-select
                v-model="couponForm.categoryIds"
                :data="categoryList"
                :props="cascaderProps"
                :render-after-expand="false"
                multiple
                style="width: 300px"
              />
              <div style="font-size: 12px; color: #999">请选择商品的品类</div>
            </div>
          </el-form-item>
        </template>
        <template v-if="couponForm.couponType === 2">
          <el-form-item style="margin-top: -10px">
            <el-button type="primary" @click="onTapSelectProduct">选择商品</el-button>
          </el-form-item>
          <div
            v-if="couponForm.productList && couponForm.productList.length > 0"
            style="width: 80%; margin: -10px auto 10px"
          >
            <el-table :data="couponForm.productList" style="width: 100%">
              <el-table-column label="商品信息" width="300">
                <template #default="scope">
                  <div style="display: flex; align-items: center">
                    <img :src="scope.row.image" alt="" style="width: 60px; height: 60px" />
                    <div
                      style="
                        font-size: 12px;
                        margin-left: 10px;
                        display: -webkit-box;
                        -webkit-box-orient: vertical;
                        overflow: hidden;
                        text-overflow: ellipsis;
                        line-height: 1.5; /* 可选：调整行高控制整体高度 */
                        max-height: 3em; /* 2行 * 行高1.5 = 3em，可选但推荐配合使用 */
                      "
                    >
                      {{ scope.row.productName }}
                    </div>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="价格" prop="price" />
              <el-table-column label="库存" prop="stock" />
              <el-table-column label="操作">
                <template #default="scope">
                  <el-button type="danger" @click="onTapDeleteProductButton(scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </template>

        <el-form-item label="优惠券面额:">
          <div style="display: flex; flex-direction: column">
            <el-input-number
              v-model="couponForm.denomination"
              :controls="false"
              :min="0.01"
              :precision="2"
              style="margin: 0 5px"
            />
            <div style="font-size: 12px; color: #999">面额需大于0元，支持两位小数</div>
          </div>
        </el-form-item>
        <!-- 使用门槛 -->
        <el-form-item label="使用门槛:" style="margin-top: -20px">
          <el-radio-group
            v-model="couponForm.hasThreshold"
            style="display: flex; flex-direction: column; align-items: stretch"
          >
            <el-radio :value="0" @click="couponForm.threshold = 0.01">无使用门槛</el-radio>
            <el-radio :value="1">
              订单满
              <el-input-number
                v-model="couponForm.threshold"
                :controls="false"
                :min="0.01"
                :precision="2"
                style="margin: 0 5px"
              />
              可用
            </el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 有效期模式 -->
        <el-form-item label="有效期:" style="margin-top: -10px">
          <el-radio-group v-model="couponForm.expiryType">
            <el-radio :value="0">天数</el-radio>
            <el-radio :value="1">时间段</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 有效期-天数模式 -->
        <el-form-item v-if="couponForm.expiryType === 0" style="margin-top: -10px">
          <div style="display: flex; flex-direction: column">
            <el-input-number v-model="couponForm.validDays" :controls="false" :min="1" :precision="0">
              <template #suffix>
                <span>天</span>
              </template>
            </el-input-number>
            <div style="font-size: 12px; color: #999">领取后多少天有效</div>
          </div>
        </el-form-item>
        <!-- 有效期-时间段模式（修复v-model绑定） -->
        <el-form-item v-if="couponForm.expiryType === 1" style="margin-top: -10px">
          <div>
            <el-date-picker
              v-model="couponForm.availableTime"
              end-placeholder="结束时间"
              range-separator="至"
              start-placeholder="开始时间"
              style="width: 450px"
              type="datetimerange"
              unlink-panels
            />
          </div>
        </el-form-item>

        <!-- 发布类型（数量限制） -->
        <el-form-item label="优惠券数量:" style="margin-top: -15px">
          <el-radio-group v-model="couponForm.hasQuantityLimit">
            <el-radio :value="0">限量</el-radio>
            <el-radio :value="1">不限量</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 限量时的数量输入 -->
        <el-form-item v-if="couponForm.hasQuantityLimit === 0" style="margin-top: -10px">
          <div style="display: flex; flex-direction: column">
            <el-input-number v-model="couponForm.quantityLimit" :controls="false" :min="1" :precision="0">
              <template #suffix>
                <span>张</span>
              </template>
            </el-input-number>
            <div style="font-size: 12px; color: #999">填写优惠券的发布数量</div>
          </div>
        </el-form-item>

        <!-- 用户领取数量限制 -->
        <el-form-item label="用户领取数量:" style="margin-top: -10px">
          <div style="display: flex; flex-direction: column">
            <el-input-number v-model="couponForm.userMaxCollectionLimit" :controls="false" :min="1" :precision="0">
              <template #suffix>
                <span>张</span>
              </template>
            </el-input-number>
            <div style="font-size: 12px; color: #999">每个用户可领取的数量</div>
          </div>
        </el-form-item>

        <!-- 状态开关 -->
        <el-form-item label="状态:" style="margin-top: -20px">
          <el-radio-group v-model="couponForm.couponStatus">
            <el-radio :value="0">开启</el-radio>
            <el-radio :value="1">关闭</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
    </el-scrollbar>

    <!-- 底部按钮 -->
    <template #footer>
      <div class="dialog-footer">
        <el-button v-if="props.type === 'add'" type="primary" @click="onTapSaveButton">保存</el-button>
        <el-button v-if="props.type === 'edit'" type="primary" @click="onTapUpdateButton">更新</el-button>
        <el-button @click="showCouponModal = false">取消</el-button>
      </div>
    </template>
    <el-dialog
      v-model="showProductSelectDialog"
      :close-on-click-modal="false"
      append-to-body
      draggable
      title="选择商品"
      width="800"
    >
      <el-form :model="productSearchForm">
        <el-form-item label="商品名称:">
          <el-input
            v-model="productSearchForm.productName"
            placeholder="请输入商品名称"
            style="width: 240px"
          ></el-input>
          <el-button style="margin-left: 10px" type="primary" @click="onTapSearchProductButton">查询</el-button>
        </el-form-item>
      </el-form>
      <el-table ref="productTableRef" :data="productList" max-height="450" style="width: 100%">
        <el-table-column type="selection" width="55" />
        <el-table-column label="商品信息" width="300">
          <template #default="scope">
            <div style="display: flex; align-items: center">
              <img :src="scope.row.image" alt="" style="width: 60px; height: 60px" />
              <div
                style="
                  font-size: 12px;
                  margin-left: 10px;
                  display: -webkit-box;
                  -webkit-box-orient: vertical;
                  overflow: hidden;
                  text-overflow: ellipsis;
                  line-height: 1.5; /* 可选：调整行高控制整体高度 */
                  max-height: 3em; /* 2行 * 行高1.5 = 3em，可选但推荐配合使用 */
                "
              >
                {{ scope.row.productName }}
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="价格" prop="price" />
        <el-table-column label="库存" prop="stock" />
        <el-table-column label="商品类型">
          <template #default="scope">
            <span v-if="scope.row.productType === 0">普通商品</span>
            <span v-if="scope.row.productType === 1">秒杀商品</span>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:current-page="productCurrentPage"
        v-model:page-size="productPageSize"
        :page-sizes="[10, 20, 30, 40]"
        :total="productTotal"
        layout="total, sizes, prev, pager, next, jumper"
        style="margin-top: 20px"
      />
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="onTapConfirmProduct">确认</el-button>
          <el-button @click="showProductSelectDialog = false">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </el-dialog>
</template>

<style lang="scss" scoped></style>
